{% extends "base.html" %}

{% block title %}XBot管理后台 - 系统设置{% endblock %}

{% block page_title_icon %}<i class="bi bi-gear page-title-icon"></i>{% endblock %}
{% block page_title %}系统设置{% endblock %}

{% block content %}
<!-- API配置卡片 -->
<div class="card mb-4">
    <div class="card-header d-flex justify-content-between align-items-center">
        <h5 class="card-title mb-0">API 配置</h5>
        <button class="btn btn-sm btn-primary" id="saveApiConfigBtn">
            <i class="bi bi-save"></i> 保存配置
        </button>
    </div>
    <div class="card-body">
        <form id="apiConfigForm">
            <div class="mb-3">
                <label for="apiBaseUrl" class="form-label">API 基础地址</label>
                <input type="text" class="form-control" id="apiBaseUrl" placeholder="例如: http://127.0.0.1:9011">
                <div class="form-text">微信机器人API的基础URL地址</div>
            </div>
            <div class="mb-3">
                <label for="apiTimeout" class="form-label">API 超时时间 (毫秒)</label>
                <input type="number" class="form-control" id="apiTimeout" min="1000" step="1000">
                <div class="form-text">API请求的超时时间</div>
            </div>
            <div class="mb-3">
                <label for="apiRetries" class="form-label">API 重试次数</label>
                <input type="number" class="form-control" id="apiRetries" min="0" max="5">
                <div class="form-text">API请求失败时的最大重试次数</div>
            </div>
        </form>
    </div>
</div>

<!-- 系统设置卡片 -->
<div class="card mb-4">
    <div class="card-header d-flex justify-content-between align-items-center">
        <h5 class="card-title mb-0">系统设置</h5>
        <button class="btn btn-sm btn-primary" id="saveSystemConfigBtn">
            <i class="bi bi-save"></i> 保存设置
        </button>
    </div>
    <div class="card-body">
        <form id="systemConfigForm">
            <div class="mb-3">
                <label for="logLevel" class="form-label">日志级别</label>
                <select class="form-select" id="logLevel">
                    <option value="debug">Debug (调试)</option>
                    <option value="info">Info (信息)</option>
                    <option value="warning">Warning (警告)</option>
                    <option value="error">Error (错误)</option>
                </select>
                <div class="form-text">设置系统日志记录的详细程度</div>
            </div>
            <div class="mb-3 form-check form-switch">
                <input class="form-check-input" type="checkbox" id="autoStart">
                <label class="form-check-label" for="autoStart">自动启动微信机器人</label>
                <div class="form-text">系统启动时自动连接微信机器人</div>
            </div>
            <div class="mb-3">
                <label for="dataDir" class="form-label">数据存储目录</label>
                <input type="text" class="form-control" id="dataDir">
                <div class="form-text">系统数据存储的路径（需要重启才能生效）</div>
            </div>
        </form>
    </div>
</div>

<!-- 备份与恢复卡片 -->
<div class="card">
    <div class="card-header">
        <h5 class="card-title mb-0">备份与恢复</h5>
    </div>
    <div class="card-body">
        <div class="row mb-4">
            <div class="col-md-6">
                <h6>备份数据</h6>
                <p class="text-muted">将系统数据备份到本地文件</p>
                <button class="btn btn-primary" id="backupBtn">
                    <i class="bi bi-download"></i> 创建备份
                </button>
            </div>
            <div class="col-md-6">
                <h6>恢复数据</h6>
                <p class="text-muted">从备份文件恢复系统数据</p>
                <div class="input-group">
                    <input type="file" class="form-control" id="restoreFile">
                    <button class="btn btn-warning" id="restoreBtn">
                        <i class="bi bi-upload"></i> 恢复
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 加载API配置
    loadApiConfig();
    
    // 加载系统设置
    loadSystemConfig();
    
    // 绑定事件
    document.getElementById('saveApiConfigBtn').addEventListener('click', saveApiConfig);
    document.getElementById('saveSystemConfigBtn').addEventListener('click', saveSystemConfig);
    document.getElementById('backupBtn').addEventListener('click', backupData);
    document.getElementById('restoreBtn').addEventListener('click', restoreData);
});

// 加载API配置
async function loadApiConfig() {
    try {
        const response = await fetch('/api/config');
        const data = await response.json();
        
        if (data.success) {
            document.getElementById('apiBaseUrl').value = data.data.api_base_url || '';
            document.getElementById('apiTimeout').value = data.data.api_timeout || 10000;
            document.getElementById('apiRetries').value = data.data.api_retries || 3;
        } else {
            showAlert('danger', `加载API配置失败: ${data.message || '未知错误'}`);
        }
    } catch (error) {
        console.error('加载API配置失败:', error);
        showAlert('danger', `加载API配置失败: ${error.message || '网络错误'}`);
    }
}

// 保存API配置
async function saveApiConfig() {
    const apiConfig = {
        api_base_url: document.getElementById('apiBaseUrl').value,
        api_timeout: parseInt(document.getElementById('apiTimeout').value) || 10000,
        api_retries: parseInt(document.getElementById('apiRetries').value) || 3
    };
    
    try {
        const response = await fetch('/api/config', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(apiConfig)
        });
        
        const data = await response.json();
        
        if (data.success) {
            showAlert('success', '保存API配置成功');
        } else {
            showAlert('danger', `保存失败: ${data.message || '未知错误'}`);
        }
    } catch (error) {
        console.error('保存API配置失败:', error);
        showAlert('danger', `保存失败: ${error.message || '网络错误'}`);
    }
}

// 加载系统设置
function loadSystemConfig() {
    // 模拟加载系统设置
    document.getElementById('logLevel').value = 'info';
    document.getElementById('autoStart').checked = true;
    document.getElementById('dataDir').value = './data';
}

// 保存系统设置
function saveSystemConfig() {
    // 模拟保存系统设置
    const logLevel = document.getElementById('logLevel').value;
    const autoStart = document.getElementById('autoStart').checked;
    const dataDir = document.getElementById('dataDir').value;
    
    console.log('保存系统设置:', { logLevel, autoStart, dataDir });
    
    showAlert('success', '保存系统设置成功');
}

// 备份数据
function backupData() {
    // 模拟备份操作
    showAlert('success', '数据备份成功，正在下载...');
    // 实际项目中这里应该触发一个下载操作
}

// 恢复数据
function restoreData() {
    const fileInput = document.getElementById('restoreFile');
    if (!fileInput.files.length) {
        showAlert('warning', '请先选择备份文件');
        return;
    }
    
    // 模拟恢复操作
    showAlert('success', '数据恢复成功，系统将在5秒后重启...');
}

// 显示提醒消息
function showAlert(type, message) {
    const alertDiv = document.createElement('div');
    alertDiv.className = `alert alert-${type} alert-dismissible fade show`;
    alertDiv.role = 'alert';
    alertDiv.innerHTML = `
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    `;
    
    document.querySelector('.content-container').insertBefore(alertDiv, document.querySelector('.content-container').firstChild);
    
    // 3秒后自动关闭
    setTimeout(() => {
        const bsAlert = new bootstrap.Alert(alertDiv);
        bsAlert.close();
    }, 3000);
}
</script>
{% endblock %} 